#include "comm.hpp"
#include "log.hpp"


void getmessage(int fd)
{
    char buffer[SIZE];
    while(true)
    {
        memset(buffer,'\0',sizeof(buffer) -1);
        ssize_t s = read(fd, buffer, sizeof(buffer)-1);
        if(s > 0)
        {
            cout << getpid() << "|||" << buffer << endl;
        }
        else if(s == 0)
        { 
            cout << "read end of file , client quit, server quit" << endl;
            break;
        }
        else
        {
            perror("read");
            break;
        }
    }

}
int main()
{
    // 1.创建管道文件
    if (mkfifo(ipcPath.c_str(), MODE) < 0)
    {
        perror("mkfifo");
        exit(1);
    }
    Log("create pipe file success",Debug) << "step 1" << endl;

    //2.打开管道文件
    int fd = open(ipcPath.c_str(), O_RDONLY);
    if(fd == -1)
    {
        perror("open");
        exit(2);
    }
    Log("open pipe file success:", Debug) << "step 2" << endl;

    //开始通信
    int numSize = 3;
    for(int i= 0; i < numSize; i++)
    {
        pid_t id = fork();
        if(id == 0)
        {
            getmessage(fd);
            exit(1);
        }
    }
    for(int i = 0; i< numSize; i++)
    {
        waitpid(-1,nullptr,0);
    }
    //3. 关闭管道文件
    close(fd);
    Log("关闭管道文件成功",Debug) << "step3" << endl;
    //4. 删除管道文件
    unlink(ipcPath.c_str());//
    Log("删除管道文件成功",Debug) << "step4" << endl;

    return 0;
}